package cn.com.device.monitor.service;

import cn.com.device.monitor.vo.MqttMessgeVO;
import org.apache.iotdb.isession.SessionDataSet;
import org.apache.iotdb.session.Session;
import org.apache.tsfile.read.common.Field;
import org.apache.tsfile.read.common.RowRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseQueryService {
    Logger logger = LoggerFactory.getLogger(BaseQueryService.class);
    @Autowired
    protected Session session;
    @Value("${iotdb.device.root}")
    private String rootNode;
    public List<MqttMessgeVO> baseQuery(String sql, String deviceId) throws Exception {
        List<MqttMessgeVO> list = new ArrayList<>();
        SessionDataSet dataSet = session.executeQueryStatement(sql);
        // 查询的字段，查询结果默认前面加了一个time字段
        List<String>  coloums =  dataSet.getColumnNames();
        while (dataSet.hasNext()) {
            MqttMessgeVO deviceVO =new MqttMessgeVO();
            deviceVO.setDeviceId(deviceId.replace(rootNode+".",""));
            RowRecord data= dataSet.next();
            List<Field> fields =  data.getFields();
            int length = fields.size();
            for(int i=0 ;i < length ; i++){
                String deviceRoots = coloums.get(i+1);
                String cloumName = deviceRoots.replace(deviceId+".","");
                java.lang.reflect.Field dataField=null;
                try{
                   dataField =  deviceVO.getClass().getDeclaredField(cloumName);
                }catch (Exception e){
                    e.getStackTrace();
                    continue;
                }
                dataField.setAccessible(true);
                Field field = fields.get(i);
                String result = field.getStringValue();
                dataField.set(deviceVO,result);
            }
            list.add(deviceVO);
        }
        return list;
    }

}
